package client.comm.baoding.fragment

import android.view.View
import androidx.lifecycle.lifecycleScope
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.comm_ui.draw.SpaceItemDecoration
import client.comm.commlib.widget.EmptyLayout
import client.comm.baoding.R
import client.comm.baoding.adapter.ZcjlAdapter
import client.comm.baoding.api.bean.Zcjl
import client.comm.baoding.databinding.FragmentLoadmorepageBinding
import client.comm.baoding.ui.vm.SfjlViewModel
import client.comm.commlib.base.PagerFooterAdapter
import client.comm.commlib.network.data.PagingJsonResult
import kotlinx.coroutines.flow.collect

class SfjlOneFragment : BaseFragment<FragmentLoadmorepageBinding, SfjlViewModel>() {
    override fun getViewId(): Int {
        return R.layout.fragment_loadmorepage
    }

    val adapter: ZcjlAdapter by lazy {
        ZcjlAdapter(requireContext(), mImgLoader).apply {
            refreshLoading = {
                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                }
            }
            refreshNotLoading = {
                binding.refreshLayout.isRefreshing = false

                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NODATA
                } else {
                    binding.emptyLayout.visibility = View.GONE
                }

            }
            refreshError = {
                if (itemCount == 0)
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
            }
        }
    }

    override fun initViewModel(): SfjlViewModel = createViewModel()

    override fun initWidget() {
        binding.emptyLayout.setOnClickListener {
            adapter.refresh()
        }
        binding.recyclerView.addItemDecoration(SpaceItemDecoration(10))

        binding.recyclerView.adapter = adapter.withLoadStateFooter(PagerFooterAdapter())
        binding.refreshLayout.setOnRefreshListener {
            adapter.refresh()
        }
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launchWhenResumed {
            viewModel.pagingDataAuto {
                val ret = viewModel.server.zcjl(it, 10)
                PagingJsonResult(
                    list = ret.body()?.data?.record_list,
                    code = ret.body()?.code,
                    message = ret.body()?.message,
                    errorStr = ret.errorBody()?.string()
                )
            }.collect {
                adapter.submitData(it)
            }
        }
    }
}